package com.atom.module.mvvm.extren

import android.widget.RadioGroup
import androidx.annotation.CheckResult
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate

@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
public fun RadioGroup.checkedChanges() = callbackFlow<Int> {
    checkMainThread()
    val listener = object : RadioGroup.OnCheckedChangeListener {
        private var lastChecked = checkedRadioButtonId
        override fun onCheckedChanged(group: RadioGroup, checkedId: Int) {
            if (checkedId != lastChecked) {
                lastChecked = checkedId
                trySend(checkedId)
            }
        }
    }
    setOnCheckedChangeListener(listener)
    awaitClose { setOnCheckedChangeListener(null) }
}
    .conflate()
    .asInitialValueFlow { checkedRadioButtonId }
